package com.mega.ycy;

import com.google.common.collect.Lists;
import com.mega.ycy.common.SubscribeEventYcy;
import com.mega.ycy.common.item.ItemAYiSlashBlade;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.*;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.HoverEvent;
import net.minecraftforge.client.event.GuiScreenEvent;
import org.lwjgl.Sys;
import org.lwjgl.input.Mouse;

import javax.annotation.Nullable;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GuiGameOver extends GuiScreen {
    public static GuiButton RESPAWN;
    public static GuiButton TITLE_SCREEN;
    private final ITextComponent causeOfDeath;
    public Minecraft mc_ = Minecraft.getMinecraft();
    public List<GuiButton> buttons = new ArrayList<>();
    protected float zLevel;
    private int enableButtonsTimer;
    private int width_;
    private int height_;
    public boolean isInited = false;
    public FontRenderer fontRenderer = new FontRenderer(mc_.gameSettings, new ResourceLocation("textures/font/ascii.png"), mc_.renderEngine, false) {
        public double rangeRemap(double value, double low1, double high1, double low2, double high2) {
            return low2 + (value - low1) * (high2 - low2) / (high1 - low1);
        }
        @Override
        public int drawStringWithShadow(String text, float x, float y, int color) {
            float huehuehue = (float) GuiGameOver.getSystemTime() / 700.0F % 1.0F;
            float huehuehueStep = (float)rangeRemap(Math.sin((double)((float)GuiGameOver.getSystemTime() / 2000.0F)) % 6.28318D, -1.0D, 1.0D, 0.01D, 0.15D);

            for(int i = 0; i < text.length(); ++i) {
                int c = color & -16777216 | MathHelper.hsvToRGB(huehuehue, 0.5F, 1.0F);
                float yOffset = (float)Math.sin((double)((float)i + (float)Minecraft.getSystemTime() / 300.0F));
                x = (float)super.drawStringWithShadow(String.valueOf(text.charAt(i)), x, y + yOffset, c);
                huehuehue += huehuehueStep;
                huehuehue %= 1.0F;
            }

            return (int)x;
        }
    };

    public static long getSystemTime() {
        return Sys.getTime() * 1000L / Sys.getTimerResolution();
    }


    public GuiGameOver(@Nullable ITextComponent causeOfDeathIn) {
        causeOfDeath = causeOfDeathIn;
        mc = Minecraft.getMinecraft();
    }

    @SuppressWarnings("ALL")
    public static void drawRect(int left, int top, int right, int bottom, int color) {
        if (left < right) {
            int i = left;
            left = right;
            right = i;
        }

        if (top < bottom) {
            int j = top;
            top = bottom;
            bottom = j;
        }

        float f3 = (float) (color >> 24 & 255) / 255.0F;
        float f = (float) (color >> 16 & 255) / 255.0F;
        float f1 = (float) (color >> 8 & 255) / 255.0F;
        float f2 = (float) (color & 255) / 255.0F;
        Tessellator tessellator = Tessellator.getInstance();
        BufferBuilder bufferbuilder = tessellator.getBuffer();
        GlStateManager.enableBlend();
        GlStateManager.disableTexture2D();
        GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
        GlStateManager.color(f, f1, f2, f3);
        bufferbuilder.begin(7, DefaultVertexFormats.POSITION);
        bufferbuilder.pos((double) left, (double) bottom, 0.0D).endVertex();
        bufferbuilder.pos((double) right, (double) bottom, 0.0D).endVertex();
        bufferbuilder.pos((double) right, (double) top, 0.0D).endVertex();
        bufferbuilder.pos((double) left, (double) top, 0.0D).endVertex();
        tessellator.draw();
        GlStateManager.enableTexture2D();
        GlStateManager.disableBlend();
    }

    public void init() {
        isInited = true;
        mc_ = Minecraft.getMinecraft();
        itemRender = mc_.getRenderItem();
        ScaledResolution res = new ScaledResolution(mc_);
        width_ = res.getScaledWidth();
        height_ = res.getScaledHeight();
        if (RESPAWN == null)
            RESPAWN = new GuiButton(0, width_ / 2 - 100, height_ / 4 + 72, I18n.format("deathScreen.respawn"));
        if (TITLE_SCREEN == null)
            TITLE_SCREEN = new GuiButton(1, width_ / 2 - 100, height_ / 4 + 96, I18n.format("deathScreen.titleScreen"));
        enableButtonsTimer = 0;
        RESPAWN.enabled = TITLE_SCREEN.enabled = false;
    }

    @SubscribeEventYcy
    public void renderScreen() {
        if (isInited) {
            int k1 = Mouse.getX() * width_ / mc.displayWidth;
            int l1 = height_ - Mouse.getY() * height_ / mc.displayHeight - 1;
            float p1 = mc_.getTickLength();
            drawScreen(k1, l1, p1);
        }
    }

    public void initGui() {
        buttons.add(RESPAWN);
        buttons.add(TITLE_SCREEN);
    }

    protected void keyTyped(char typedChar, int keyCode) {
    }

    public void actionPerformed(GuiButton button) {
        switch (button.id) {
            case 0:
                mc_.player.respawnPlayer();
                mc_.displayGuiScreen(null);
                break;
            case 1:

                if (mc_.world.getWorldInfo().isHardcoreModeEnabled()) {
                    mc_.displayGuiScreen(new GuiMainMenu());
                } else {
                    GuiYesNo guiyesno = new GuiYesNo(this, I18n.format("deathScreen.quit.confirm"), "", I18n.format("deathScreen.titleScreen"), I18n.format("deathScreen.respawn"), 0);
                    mc_.displayGuiScreen(guiyesno);
                    guiyesno.setButtonDelay(20);
                }
        }
    }

    public void confirmClicked(boolean result, int id) {
        if (result) {
            if (mc_.world != null) {
                mc_.world.sendQuittingDisconnectingPacket();
            }

            mc_.loadWorld(null);
            mc_.displayGuiScreen(new GuiMainMenu());
        } else {
            mc_.player.respawnPlayer();
            mc_.displayGuiScreen(null);
        }
    }

    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        if (Mouse.isButtonDown(MouseEvent.MOUSE_CLICKED)) {
            if (RESPAWN.isMouseOver()) {
                if (Minecraft.getMinecraft().player != null) {
                    ItemAYiSlashBlade.ycy_death2.remove(Minecraft.getMinecraft().player);
                    ItemAYiSlashBlade.ycy_death.remove(Minecraft.getMinecraft().player.entityUniqueID);
                    Minecraft.getMinecraft().player.respawnPlayer();
                }
            }
            if (TITLE_SCREEN.isMouseOver()) {
                if (mc_.world != null) {
                    mc_.world.sendQuittingDisconnectingPacket();
                }

                mc_.loadWorld(null);
                mc_.displayGuiScreen(new GuiMainMenu());
            }
        }
        drawGradientRect(0, 0, width_, height_, 1615855616, -1602211792);
        GlStateManager.pushMatrix();
        GlStateManager.scale(2.0F, 2.0F, 2.0F);
        drawCenteredString(fontRenderer, I18n.format("deathScreen.title"), width_ / 2 / 2, 30, 16777215);
        GlStateManager.popMatrix();

        if (causeOfDeath != null) {
            drawCenteredString(fontRenderer, causeOfDeath.getFormattedText(), width_ / 2, 85, 16777215);
        }

        drawCenteredString(fontRenderer, I18n.format("deathScreen.score") + ": " + TextFormatting.YELLOW + mc_.player.getScore(), width_ / 2, 100, 16777215);

        if (causeOfDeath != null && mouseY > 85 && mouseY < 85 + fontRenderer.FONT_HEIGHT) {
            ITextComponent itextcomponent = getClickedComponentAt(mouseX);

            if (itextcomponent != null && itextcomponent.getStyle().getHoverEvent() != null) {
                handleComponentHover(itextcomponent, mouseX, mouseY);
            }
        }
        RESPAWN.drawButton(mc_, mouseX, mouseY, partialTicks);
        TITLE_SCREEN.drawButton(mc_, mouseX, mouseY, partialTicks);
        drawHoveringText_(Collections.singletonList("RETURN THE SEA"), mouseX, mouseY, fontRenderer);

    }

    @SuppressWarnings("ALL")
    public void drawHoveringText(List<String> textLines, int x, int y) {
        drawHoveringText_(textLines, x, y, fontRenderer);
    }

    @SuppressWarnings("ALL")
    protected void drawHoveringText_(List<String> textLines, int x, int y, FontRenderer font) {
        net.minecraftforge.fml.client.config.GuiUtils.drawHoveringText(textLines, x, y, width_, height_, -1, font);
        if (false && !textLines.isEmpty()) {
            GlStateManager.disableRescaleNormal();
            RenderHelper.disableStandardItemLighting();
            GlStateManager.disableLighting();
            GlStateManager.disableDepth();
            int i = 0;

            for (String s : textLines) {
                int j = fontRenderer.getStringWidth(s);

                if (j > i) {
                    i = j;
                }
            }

            int l1 = x + 12;
            int i2 = y - 12;
            int k = 8;

            if (textLines.size() > 1) {
                k += 2 + (textLines.size() - 1) * 10;
            }

            if (l1 + i > width_) {
                l1 -= 28 + i;
            }

            if (i2 + k + 6 > height_) {
                i2 = height_ - k - 6;
            }

            zLevel = 300.0F;
            itemRender.zLevel = 300.0F;
            int l = -267386864;
            int system_time = (int) Minecraft.getSystemTime() / 1000 % 1;
            int system_time2 = (int) Minecraft.getSystemTime() / 996 % 1;
            drawGradientRect(l1 - 3, i2 - 4, l1 + i + 3, i2 - 3, system_time, system_time2);
            drawGradientRect(l1 - 3, i2 + k + 3, l1 + i + 3, i2 + k + 4, system_time, system_time2);
            drawGradientRect(l1 - 3, i2 - 3, l1 + i + 3, i2 + k + 3, system_time, system_time2);
            drawGradientRect(l1 - 4, i2 - 3, l1 - 3, i2 + k + 3, system_time, system_time2);
            drawGradientRect(l1 + i + 3, i2 - 3, l1 + i + 4, i2 + k + 3, system_time, system_time2);
            int i1 = 1347420415;
            int j1 = 1344798847;
            drawGradientRect(l1 - 3, i2 - 3 + 1, l1 - 3 + 1, i2 + k + 3 - 1, system_time, system_time2);
            drawGradientRect(l1 + i + 2, i2 - 3 + 1, l1 + i + 3, i2 + k + 3 - 1, system_time, system_time2);
            drawGradientRect(l1 - 3, i2 - 3, l1 + i + 3, i2 - 3 + 1, system_time, system_time2);
            drawGradientRect(l1 - 3, i2 + k + 2, l1 + i + 3, i2 + k + 3, system_time, system_time);

            for (int k1 = 0; k1 < textLines.size(); ++k1) {
                String s1 = textLines.get(k1);
                drawString(fontRenderer, s1, l1, i2, -1);

                if (k1 == 0) {
                    i2 += 2;
                }

                i2 += 10;
            }

            zLevel = 0.0F;
            itemRender.zLevel = 0.0F;
            GlStateManager.enableLighting();
            GlStateManager.enableDepth();
            RenderHelper.enableStandardItemLighting();
            GlStateManager.enableRescaleNormal();
        }
    }

    @SuppressWarnings("ALL")
    protected void handleComponentHover(ITextComponent component, int x, int y) {
        if (component != null && component.getStyle().getHoverEvent() != null) {
            HoverEvent hoverevent = component.getStyle().getHoverEvent();

            if (hoverevent.getAction() == HoverEvent.Action.SHOW_ITEM) {
                ItemStack itemstack = ItemStack.EMPTY;

                try {
                    NBTBase nbtbase = JsonToNBT.getTagFromJson(hoverevent.getValue().getUnformattedText());

                    if (nbtbase instanceof NBTTagCompound) {
                        itemstack = new ItemStack((NBTTagCompound) nbtbase);
                    }
                } catch (NBTException var9) {
                    ;
                }

                if (itemstack.isEmpty()) {
                    drawHoveringText(TextFormatting.RED + "Invalid Item!", x, y);
                } else {
                    renderToolTip(itemstack, x, y);
                }
            } else if (hoverevent.getAction() == HoverEvent.Action.SHOW_ENTITY) {
                if (mc_.gameSettings.advancedItemTooltips) {
                    try {
                        NBTTagCompound nbttagcompound = JsonToNBT.getTagFromJson(hoverevent.getValue().getUnformattedText());
                        List<String> list = Lists.<String>newArrayList();
                        list.add(nbttagcompound.getString("name"));

                        if (nbttagcompound.hasKey("type", 8)) {
                            String s = nbttagcompound.getString("type");
                            list.add("Type: " + s);
                        }

                        list.add(nbttagcompound.getString("id"));
                        drawHoveringText(list, x, y);
                    } catch (NBTException var8) {
                        drawHoveringText(TextFormatting.RED + "Invalid Entity!", x, y);
                    }
                }
            } else if (hoverevent.getAction() == HoverEvent.Action.SHOW_TEXT) {
                drawHoveringText(fontRenderer.listFormattedStringToWidth(hoverevent.getValue().getFormattedText(), Math.max(width_ / 2, 200)), x, y);
            }

            GlStateManager.disableLighting();
        }
    }

    @Nullable
    public ITextComponent getClickedComponentAt(int p_184870_1_) {
        if (causeOfDeath != null) {
            int i = fontRenderer.getStringWidth(causeOfDeath.getFormattedText());
            int j = width_ / 2 - i / 2;
            int k = width_ / 2 + i / 2;
            int l = j;

            if (p_184870_1_ >= j && p_184870_1_ <= k) {
                for (ITextComponent itextcomponent : causeOfDeath) {
                    l += fontRenderer.getStringWidth(GuiUtilRenderComponents.removeTextColorsIfConfigured(itextcomponent.getUnformattedComponentText(), false));

                    if (l > p_184870_1_) {
                        return itextcomponent;
                    }
                }

            }
        }
        return null;
    }

    public void setWorldAndResolution(Minecraft mc, int width, int height) {
        mc_ = mc;
        itemRender = mc_.getRenderItem();
        width_ = width;
        height_ = height;
        if (RESPAWN == null)
            RESPAWN = new GuiButton(0, width_ / 2 - 100, height_ / 4 + 72, I18n.format("deathScreen.respawn"));
        if (TITLE_SCREEN == null)
            TITLE_SCREEN = new GuiButton(1, width_ / 2 - 100, height_ / 4 + 96, I18n.format("deathScreen.titleScreen"));

        initGui();
    }

    public void setGuiSize(int w, int h) {
        if (w < 100 || h < 100)
            return;
        width_ = w;
        height_ = h;
    }

    @Override
    public void onResize(Minecraft mcIn, int w, int h) {
        if (w < 100 || h < 100)
            return;
        super.onResize(mcIn, w, h);
    }

    public boolean doesGuiPauseGame() {
        return false;
    }

    public void updateScreen() {
        ++enableButtonsTimer;

        if (enableButtonsTimer == 20) {
            RESPAWN.enabled = TITLE_SCREEN.enabled = true;
        }
    }

    @SuppressWarnings("ALL")
    protected void drawHorizontalLine(int startX, int endX, int y, int color) {
        if (endX < startX) {
            int i = startX;
            startX = endX;
            endX = i;
        }

        drawRect(startX, y, endX + 1, y + 1, color);
    }

    @SuppressWarnings("ALL")
    protected void drawVerticalLine(int x, int startY, int endY, int color) {
        if (endY < startY) {
            int i = startY;
            startY = endY;
            endY = i;
        }

        drawRect(x, startY + 1, x + 1, endY, color);
    }

    @SuppressWarnings("ALL")
    protected void drawGradientRect(int left, int top, int right, int bottom, int startColor, int endColor) {
        float f = (float) (startColor >> 24 & 255) / 255.0F;
        float f1 = (float) (startColor >> 16 & 255) / 255.0F;
        float f2 = (float) (startColor >> 8 & 255) / 255.0F;
        float f3 = (float) (startColor & 255) / 255.0F;
        float f4 = (float) (endColor >> 24 & 255) / 255.0F;
        float f5 = (float) (endColor >> 16 & 255) / 255.0F;
        float f6 = (float) (endColor >> 8 & 255) / 255.0F;
        float f7 = (float) (endColor & 255) / 255.0F;
        GlStateManager.disableTexture2D();
        GlStateManager.enableBlend();
        GlStateManager.disableAlpha();
        GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
        GlStateManager.shadeModel(7425);
        Tessellator tessellator = Tessellator.getInstance();
        BufferBuilder bufferbuilder = tessellator.getBuffer();
        bufferbuilder.begin(7, DefaultVertexFormats.POSITION_COLOR);
        bufferbuilder.pos((double) right, (double) top, (double) zLevel).color(f1, f2, f3, f).endVertex();
        bufferbuilder.pos((double) left, (double) top, (double) zLevel).color(f1, f2, f3, f).endVertex();
        bufferbuilder.pos((double) left, (double) bottom, (double) zLevel).color(f5, f6, f7, f4).endVertex();
        bufferbuilder.pos((double) right, (double) bottom, (double) zLevel).color(f5, f6, f7, f4).endVertex();
        tessellator.draw();
        GlStateManager.shadeModel(7424);
        GlStateManager.disableBlend();
        GlStateManager.enableAlpha();
        GlStateManager.enableTexture2D();
    }

    @SuppressWarnings("ALL")
    public void drawCenteredString(FontRenderer fontRendererIn, String text, int x, int y, int color) {
        fontRendererIn.drawStringWithShadow(text, (float) (x - fontRendererIn.getStringWidth(text) / 2), (float) y, color);
    }

    @SuppressWarnings("ALL")
    public void drawString(FontRenderer fontRendererIn, String text, int x, int y, int color) {
        fontRendererIn.drawStringWithShadow(text, (float) x, (float) y, color);
    }

    @SuppressWarnings("ALL")
    public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width_, int height_) {
        float f = 0.00390625F;
        float f1 = 0.00390625F;
        Tessellator tessellator = Tessellator.getInstance();
        BufferBuilder bufferbuilder = tessellator.getBuffer();
        bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX);
        bufferbuilder.pos((double) (x + 0), (double) (y + height_), (double) zLevel).tex((double) ((float) (textureX + 0) * 0.00390625F), (double) ((float) (textureY + height_) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (x + width_), (double) (y + height_), (double) zLevel).tex((double) ((float) (textureX + width_) * 0.00390625F), (double) ((float) (textureY + height_) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (x + width_), (double) (y + 0), (double) zLevel).tex((double) ((float) (textureX + width_) * 0.00390625F), (double) ((float) (textureY + 0) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (x + 0), (double) (y + 0), (double) zLevel).tex((double) ((float) (textureX + 0) * 0.00390625F), (double) ((float) (textureY + 0) * 0.00390625F)).endVertex();
        tessellator.draw();
    }

    @SuppressWarnings("ALL")
    public void drawTexturedModalRect(float xCoord, float yCoord, int minU, int minV, int maxU, int maxV) {
        float f = 0.00390625F;
        float f1 = 0.00390625F;
        Tessellator tessellator = Tessellator.getInstance();
        BufferBuilder bufferbuilder = tessellator.getBuffer();
        bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX);
        bufferbuilder.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) maxV), (double) zLevel).tex((double) ((float) (minU + 0) * 0.00390625F), (double) ((float) (minV + maxV) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (xCoord + (float) maxU), (double) (yCoord + (float) maxV), (double) zLevel).tex((double) ((float) (minU + maxU) * 0.00390625F), (double) ((float) (minV + maxV) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (xCoord + (float) maxU), (double) (yCoord + 0.0F), (double) zLevel).tex((double) ((float) (minU + maxU) * 0.00390625F), (double) ((float) (minV + 0) * 0.00390625F)).endVertex();
        bufferbuilder.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), (double) zLevel).tex((double) ((float) (minU + 0) * 0.00390625F), (double) ((float) (minV + 0) * 0.00390625F)).endVertex();
        tessellator.draw();
    }

    @SuppressWarnings("ALL")
    public void drawTexturedModalRect(int xCoord, int yCoord, TextureAtlasSprite textureSprite, int widthIn, int heightIn) {
        Tessellator tessellator = Tessellator.getInstance();
        BufferBuilder bufferbuilder = tessellator.getBuffer();
        bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX);
        bufferbuilder.pos((double) (xCoord + 0), (double) (yCoord + heightIn), (double) zLevel).tex((double) textureSprite.getMinU(), (double) textureSprite.getMaxV()).endVertex();
        bufferbuilder.pos((double) (xCoord + widthIn), (double) (yCoord + heightIn), (double) zLevel).tex((double) textureSprite.getMaxU(), (double) textureSprite.getMaxV()).endVertex();
        bufferbuilder.pos((double) (xCoord + widthIn), (double) (yCoord + 0), (double) zLevel).tex((double) textureSprite.getMaxU(), (double) textureSprite.getMinV()).endVertex();
        bufferbuilder.pos((double) (xCoord + 0), (double) (yCoord + 0), (double) zLevel).tex((double) textureSprite.getMinU(), (double) textureSprite.getMinV()).endVertex();
        tessellator.draw();
    }
}